'use strict';
module.exports = {
	/**
	 * 修改资源
	 * @url client/resource/kh/update 前端调用的url参数地址
	 * data 请求参数 说明
	 * @param {String} _id  ID
	 * @param {Object} data  对象
	 */
	main: async (event) => {
		let { data = {}, userInfo, util, filterResponse, originalParam } = event;
		let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
		let { uid } = data;
		let res = { code: 0, msg: "" };
		// 业务逻辑开始-----------------------------------------------------------
		let { _id, is_top } = data;
		
		let pattern = /<img.+?src="(.+?)".*?>/g;
		
		let dbName = "db-resource";
		
		let dbRes = await vk.baseDao.findById({
			dbName,
			id: _id
		})
		
		if(!vk.pubfn.isNull(dbRes)) {
			data["status"] = 0;
			delete data["_id"];
			delete data["client"];
			delete data["wx_openid"];
			
			let fileList = [];
			
			if(vk.pubfn.isNull(is_top)) {
				let match, fileListA = [dbRes.resource_cover], fileListB = [data.resource_cover];
				while (match = pattern.exec(dbRes.content)) {
					let url = match[1];
					fileListA.push(url)
				}
				while (match = pattern.exec(data.content)) {
					let url = match[1];
					fileListB.push(url)
				}
				fileListA.forEach((item, index) => {
					if(!fileListB.includes(item)) {
						fileList.push(item)
					}
				})
			}
		
			res["data"] = await vk.baseDao.updateAndReturn({
				dbName,
				whereJson: {
					_id: _id,
					uid: userInfo._id
				},
				dataJson: data
			})
			
			if(vk.pubfn.isNull(is_top) && fileList.length > 0) {
				await vk.callFunction({
					url: 'admin/upload/pub/delete',
					data: {
						image: fileList
					}
				})
			}
		} else {
			res["code"] = -1;
			res["msg"] = "更新失败或不存在！";
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
